<template>
  <div>
    <div v-if="loading" class="loading-mask">
      <div class="spinner">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>
    </div>

    <el-form ref="form" :model="form" :rules="rules" label-width="90px" class="info-form">
      <div class="form-title">
        <i class="el-icon-user"></i>
        <span>个人基本信息</span>
        <div class="title-line"></div>
      </div>

      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="form.nickName" placeholder="请输入您的昵称" maxlength="30">
          <template #prefix><i class="el-icon-user"></i></template>
        </el-input>
      </el-form-item>

      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11">
          <template #prefix><i class="el-icon-phone"></i></template>
        </el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱地址" maxlength="50">
          <template #prefix><i class="el-icon-message"></i></template>
        </el-input>
      </el-form-item>

      <el-form-item label="性别">
        <el-radio-group v-model="form.sex" class="gender-group">
          <el-radio label="0" class="gender-item">
            <i class="el-icon-man"></i> 男
          </el-radio>
          <el-radio label="1" class="gender-item">
            <i class="el-icon-woman"></i> 女
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 游客信息（乡村出行相关） -->
      <template v-if="isTouristRole">
        <div class="form-section">
          <i class="el-icon-map-marker"></i>
          <span>乡村出行信息</span>
        </div>

        <el-form-item label="真实姓名" prop="tourist.name">
          <el-input v-model="form.tourist.name" placeholder="请输入真实姓名" maxlength="50">
            <template #prefix><i class="el-icon-id-card"></i></template>
          </el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="tourist.age">
          <el-input v-model="form.tourist.age" placeholder="请输入年龄" type="number">
            <template #prefix><i class="el-icon-calendar"></i></template>
          </el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="tourist.idCard">
          <el-input v-model="form.tourist.idCard" placeholder="请输入身份证号" maxlength="18">
            <template #prefix><i class="el-icon-lock"></i></template>
          </el-input>
        </el-form-item>

        <el-form-item label="常住省份" prop="tourist.province">
          <el-input v-model="form.tourist.province" placeholder="请输入所在省份" maxlength="50">
            <template #prefix><i class="el-icon-location"></i></template>
          </el-input>
        </el-form-item>

        <el-form-item label="常住城市" prop="tourist.city">
          <el-input v-model="form.tourist.city" placeholder="请输入所在城市" maxlength="50">
            <template #prefix><i class="el-icon-map"></i></template>
          </el-input>
        </el-form-item>

        <el-form-item label="乡村偏好" prop="tourist.remark">
          <el-input
            v-model="form.tourist.remark"
            type="textarea"
            rows="3"
            placeholder="请输入您喜欢的乡村类型或出行偏好（如：田园风光、民俗体验等）"
          ></el-input>
        </el-form-item>
      </template>

      <el-form-item class="form-actions">
        <el-button type="primary" @click="submit" class="btn-save">
          <i class="el-icon-check"></i> 保存信息
        </el-button>
        <el-button @click="close" class="btn-cancel">
          <i class="el-icon-undo"></i> 取消
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 脚本部分保持不变
import { updateUserProfile } from "@/api/system/user";
import { getTourist, updateTourist } from "@/api/system/tourist";
import { getUserRoles } from "@/api/system/user";

export default {
  props: {
    user: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      form: {
        nickName: "",
        phonenumber: "",
        email: "",
        sex: "0",
        tourist: {
          id: "",
          name: "",
          age: null,
          idCard: "",
          province: "",
          city: "",
          remark: ""
        }
      },
      isTouristRole: false,
      loading: true,
      baseRules: {
        nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { type: "email", message: "请输入正确邮箱格式", trigger: ["blur", "change"] }
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确手机号", trigger: "blur" }
        ]
      },
      touristRules: {
        "tourist.name": [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        "tourist.idCard": [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: "请输入正确身份证号", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    rules() {
      return this.isTouristRole ? { ...this.baseRules, ...this.touristRules } : this.baseRules;
    }
  },
  watch: {
    user: {
      handler(user) {
        if (user?.userId) {
          this.initializeForm(user);
          this.loadUserRole(user.userId);
        } else {
          this.loading = false;
        }
      },
      immediate: true
    }
  },
  methods: {
    initializeForm(user) {
      this.form = {
        nickName: user.nickName || "",
        phonenumber: user.phonenumber || "",
        email: user.email || "",
        sex: user.sex || "0",
        tourist: {
          id: user.userId || "",
          name: user.nickName || "",
          ...user.tourist
        }
      };
    },
    loadUserRole(userId) {
      getUserRoles(userId)
        .then(response => {
          this.isTouristRole = response.data.some(role => role.roleId === 2);
          if (this.isTouristRole) return this.getTouristInfo(userId);
        })
        .catch(() => this.$message.error("获取角色信息失败"))
        .finally(() => (this.loading = false));
    },
    getTouristInfo(userId) {
      return getTourist(userId).then(response => {
        if (response.data) this.form.tourist = { ...this.form.tourist, ...response.data };
      });
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          updateUserProfile(this.form)
            .then(() => {
              if (this.isTouristRole) {
                this.form.tourist.gender = this.form.sex === "0" ? "男" : "女";
                this.form.tourist.phone = this.form.phonenumber;
                this.form.tourist.email = this.form.email;
                return updateTourist(this.form.tourist);
              }
              return Promise.resolve();
            })
            .then(() => {
              this.$message.success("信息保存成功");
              this.$emit("info-updated", this.form);
            })
            .catch(() => this.$message.error("保存失败，请重试"));
        }
      });
    },
    close() {
      this.$tab.closePage();
    }
  }
};
</script>

<style scoped lang="scss">
$color-primary: #4CAF50;
$color-secondary: #8D6E63;

.info-form {
  padding: 20px;
  background-color: #fcfcfc;
  border-radius: 6px;
  border: 1px solid #f5f5f5;

  .form-title {
    display: flex;
    align-items: center;
    color: $color-secondary;
    font-size: 16px;
    margin-bottom: 20px;

    i {
      color: $color-primary;
      margin-right: 8px;
    }

    .title-line {
      flex-grow: 1;
      height: 1px;
      background-color: #f5f5f5;
      margin-left: 10px;
    }
  }

  .form-section {
    display: flex;
    align-items: center;
    color: $color-secondary;
    font-size: 15px;
    margin: 25px 0 15px;
    padding-left: 5px;

    i {
      color: $color-primary;
      margin-right: 8px;
    }
  }

  .gender-group {
    display: flex;
    gap: 20px;

    .gender-item {
      display: flex;
      align-items: center;

      i {
        margin-right: 5px;
        color: $color-primary;
      }
    }
  }

  .form-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }

  .btn-save {
    background-color: $color-primary;
    border-color: $color-primary;

    &:hover {
      background-color: #388e3c;
    }
  }

  .btn-cancel {
    background-color: white;
    color: $color-secondary;
    border-color: #e0e0e0;

    &:hover {
      background-color: #f5f5f0;
    }
  }

  // 将 ::v-deep 改为 :deep()
  :deep(.el-input__prefix) {
    color: $color-primary;
  }
}

// 加载动画
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;

  .spinner {
    display: flex;
    align-items: center;
    color: $color-primary;

    i {
      font-size: 24px;
      margin-right: 10px;
      animation: spin 1.5s linear infinite;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
